<template>
	<view class="page-box">
		<view class="jianbian">
			<!-- 搜索框 -->
			<view class="search-container">
				<Search v-model:modelValue="currentWord" v-model:searchCate="tabsIndex"></Search>
			</view>

			<view>
				<!-- tabs标签 -->
				<view class="tabs-container">
					<up-tabs :list="list" @click="shiftTab" :current="tabsIndex"
						:inactiveStyle="{ color: '#606266',fontSize:'14px', transform: 'scale(1)' }"
						:activeStyle="{ color: '#303133', fontWeight: 'bold',fontSize:'14px', transform: 'scale(1.05)' }"
						itemStyle="height: 2rem; width:100%;padding:0.3rem;" lineColor="#303133" lineWidth="70" />
				</view>
				<!-- -->
				<scroll-view scroll-y class="scroll-box">
					<view v-show="tabsIndex === 0" v-if="haveResult == '1'">
						<view class="hot-box">
							<!-- 系列列表 -->
							<view class="hot-list">
								<scroll-view scroll-y class="list-scroll">
									<view class="list-box">
										<view v-for="(item,index) in products" :key="index" class="product-style"
											@click="goListPage(item.productIdCode)">
											<view>
												<image :src="item.productImageSign" class="image-style"></image>
											</view>
											<view class="name-style">{{item.productName}}</view>
										</view>
									</view>
								</scroll-view>
							</view>
						</view>
					</view>
					<view v-show="tabsIndex === 0" v-else>
						<view class="not-result-box">
							<view class="content-box">
								<image src="/static/logo/dpl.png " class="logo-style"></image>
								<view class="text-style">{{$t('noProduct')}}</view>
							</view>
						</view>
					</view>
					<view v-show="tabsIndex === 1" v-if="haveResult == '1'">
						<view class="products-link">
							<likeCard :post="post" v-for="(post, index) in posts" :key="index"
								style="min-width:calc(50% - 0.5rem);flex: 1;margin: 0.25rem;" />
						</view>
					</view>
					<view v-show="tabsIndex === 1" v-else>
						<view class="not-result-box">
							<view class="content-box">
								<image src="/static/logo/dpl.png " class="logo-style"></image>
								<view class="text-style">{{$t('noPost')}}</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, computed, onMounted, watch, watchEffect } from "vue";
	import Search from '@/components/search.vue';
	import { useI18n } from 'vue-i18n'
	import likeCard from '@/components/linkCard.vue';
	import { onLoad } from '@dcloudio/uni-app'
	import { useCommonStore } from "../../stores/useCommonStore";
	import { searchProduct  } from '../../api/productList.js'

	const haveResult = ref<Number>(0)
	// onLoad((options : { haveProduct ?: string }) => {
	// 	// 获取 URL 参数中的 haveProduct
	// 	if (Object.prototype.hasOwnProperty.call(options, 'haveProduct')) {
	// 		haveResult.value = Number(options.haveProduct) || 0  // 空值也赋值
	// 	}
	// })
	const commonStore = useCommonStore();
	const tabsIndex = ref<number>(Number(commonStore.tabsIndex))

	onMounted(() => {
		// 获取商品数据
		// products.value = commonStore.searchProductList
	});
	// 监听store中searchProductList的变化并同步到本地状态
	watchEffect(() => {
		products.value = commonStore.searchProductList
		console.log('产品列表已更新')
		if(products.value.length!=0){
			haveResult.value =1
		}
	})
	const { t } = useI18n()
	const currentWord = ref(commonStore.keyWord)

	type tabListItemType = {
		name : string,
		badge ?: object
	}
	const list = ref<Array<tabListItemType>>([
		{ name: t('blindBoxSeries') },
		{ name: t('square') },
	])
	const params = ref({
		current: 1,
		// lang: uni.getStorageSync('lang'),
		product_name: ''
	});
	const haveProduct = ref<Number>(0)
	function goResultPage() {
		uni.navigateTo({
			url: `/pages/search/searchResult?haveProduct=${String(haveProduct.value)}`,
		})
	}
	// 定义方法 切换tab时，也触发搜索
	function shiftTab(item : any) {
		tabsIndex.value = item.index
		// 请求数据
		if (item.index == "0") {
			console.log("搜索盲盒", params.value)
			commonStore.setTabsIndex('0')
			params.value.product_name = currentWord.value
			getMenuList(params.value);
		}
		else if (item.index == "1") {
			// 搜索广场
			console.log("搜索广场")
			commonStore.setTabsIndex('1')
			haveProduct.value = 1
			goResultPage()
		}
	}
	interface SearchProduct {
			productIdCode: string,
			productName: string,
			productImageSign?: string,
		}
	const products = ref<SearchProduct[]>([])

	interface Post {
		image : string,
		desc : string,
		likes : number,
		userName : string,
	}
	const posts = ref<Post[]>([])
	function goListPage(id : string) {
		commonStore.select(id)
		// switchTab navigateTo
		uni.switchTab({
			url: `/pages/list/list?id=${id}`
		})
	}
	async function getMenuList(customParams : { current : number; product_name: string }) {
		const defaultParams = {
			current: 1,
		};
		const finalParams = {
			...defaultParams,
			...customParams
		};
		// if (uni.getStorageSync('lang') == "") {
		// 	finalParams.lang = "cn"
		// }
		console.log("参数", finalParams)
		try {
			const response = await searchProduct (finalParams)
			if (response.code == 200 && response.msg == "success") {
				// 默认图片URL
				const DEFAULT_PRODUCT_IMAGE = '/static/images/dog.jpg';
				products.value = response.data.map((item : any) => ({
					...item,
					productImageSign: item.productImageSign || DEFAULT_PRODUCT_IMAGE, // 如果没有url，则添加默认值
				}));
				console.log("搜索结果", products.value)
				// 将数据存入 store
				commonStore.setSearchProductList(products.value);
				haveProduct.value = 1
				goResultPage()
			} else {
				haveProduct.value = 0
				goResultPage()
				// 显示提示框 商品不存在
				// isShow.value = true
				// title.value = response.msg
			}
		} catch (error) {
			// '加载失败:'
			let errorMsg = t('loadFail');
			// 尝试从错误对象中获取更具体的信息
			if (error.message) {
				errorMsg += error.message;
			} else if (typeof error === 'string') {
				errorMsg += error;
			}
			haveProduct.value = 0
			goResultPage()
			// isShow.value = true
			// title.value = errorMsg
		}
	}
</script>

<style scoped lang="scss">
	.page-box {
		width: 100%;
		height: 100%;
		/*微信小程序无法使用本地资源图片作为背景图 使用base64格式*/
		background-image: url('');
		background-size: cover;
		background-repeat: no-repeat;
	}

	.jianbian {
		width: 100%;
		height: 100%;
		box-sizing: border-box;
		padding: 1.5rem 0 0;
		/* #ifdef  MP-WEIXIN*/
		padding-top: 3.5rem;
		/* #endif*/
		background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 1) 38%, rgba(255, 255, 255, 1) 100%);
	}

	.search-container {
		flex-shrink: 0;
		/* 防止搜索框被压缩*/
	}

	.tabs-container {
		width: 60%;
		margin-top: 1.5rem;
	}

	.scroll-box {
		position: absolute;
		top: 9rem;
		bottom: 0;
		width: 100%;
		padding-bottom: 1rem;
		box-sizing: border-box;

		/* #ifdef MP-WEIXIN*/
		top: 9rem;
		/* #endif */
	}

	.products-link {
		display: flex;
		flex-wrap: wrap;
		width: 96%;
		margin: 0.5rem auto;
	}

	.hot-box {
		height: calc(100% - 13.5rem);
		padding: 0 1rem;
	}

	.hot-list {
		height: 100%;
	}

	.list-scroll {
		height: 100%;
	}

	.list-box {
		display: flex;
		flex-wrap: wrap;
		justify-content: start;
	}

	.product-style {
		width: calc((100% - 3rem) / 3);
		margin: 1.2rem 0.5rem;
		text-align: center;
	}

	.image-style {
		width: 4.38rem;
		height: 4.38rem;
		border-radius: 50%;
	}

	.name-style {
		height: 1.06rem;
		line-height: 1.06rem;
		color: rgba(16, 16, 16, 1);
		font-size: 0.75rem;
		text-align: center;
	}

	.not-result-box {
		width: 100%;
		height: 20rem;
		margin-top: 3rem;
		padding: 2rem;
		box-sizing: border-box;
	}

	.content-box {
		width: 100%;
		margin: 0 auto;
		text-align: center;
	}

	.logo-style {
		width: 7.56rem;
		height: 7.38rem;
	}

	.text-style {
		height: 1.25rem;
		line-height: 1.25rem;
		font-size: 0.88rem;
		text-align: center;
	}
</style>